package org.alvin;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class Pdf2Png {

    public static void main1(String[] args) {
        File file = new File("D:\\tangzhichao\\pdf_qr");
        File outDir = new File("D:\\tangzhichao\\pdf_png");
        outDir.mkdirs();

        Arrays.stream(file.listFiles()).filter(item -> {
            return item.getName().toLowerCase().endsWith(".pdf");
        }).forEach(item -> {
            File outFile = new File(outDir, item.getName().concat(".png"));
            pdf2png(item, outFile, 0, 1, "png");
        });
    }

//    public static void main2(String[] args) {
//        File outDir = new File("D:\\tangzhichao\\pdf_png");
//        File ouMinitDir = new File("D:\\tangzhichao\\png_mini");
//        ouMinitDir.mkdirs();
//        Arrays.stream(outDir.listFiles()).filter(item -> {
//            return item.getName().toLowerCase().endsWith(".png");
//        }).forEach(item -> {
//            File outFile = new File(ouMinitDir, item.getName().concat("mini.png"));
//
//            try {
//                Thumbnails.of(item)
//                        .size(200, 366)
//                        .toFile(outFile.getAbsolutePath());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        });
//    }

//    public static void main3(String[] args) {
////        File ouMinitDir = new File("D:\\tangzhichao\\png_mini");
//        File ouMinitDir = new File("D:\\tangzhichao\\pdf_png");
//        File outDir = new File("D:\\tangzhichao\\png_cut");
//        outDir.mkdirs();
//        Arrays.stream(ouMinitDir.listFiles()).filter(item -> {
//            return item.getName().toLowerCase().endsWith(".png");
//        }).forEach(item -> {
//            File outFile = new File(outDir, item.getName().concat("_cut.png"));
//            try {
////                2800 x 5120
////                Thumbnails.of(item).sourceRegion(22, 140, 200 - 46, 366 - 143 - ((200 - 44) / 2) + 24).scale(1)
////
////                        .toFile(outFile.getAbsolutePath());
//
////                  2800 x 5120
////      2483  3137
//
//                int width = 2800;
//                int height = 5120;
//                int startX = 317;
//                int startY = 1983;
//
//                Thumbnails.of(item).sourceRegion(startX, startY, width - (startX << 1), height - startY - ((width - startX) / 2) + 100).scale(1)
//                        .toFile(outFile.getAbsolutePath());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        });
//    }

    public static void main3(String[] args) {
//        File ouMinitDir = new File("D:\\tangzhichao\\png_mini");
        File ouMinitDir = new File("D:\\tangzhichao\\pdf_png");
        File outDir = new File("D:\\tangzhichao\\png_cut");
        outDir.mkdirs();
        Arrays.stream(ouMinitDir.listFiles()).filter(item -> {
            return item.getName().toLowerCase().endsWith(".png");
        }).forEach(item -> {
            File outFile = new File(outDir, item.getName().concat("_cut.png"));
            try {
//                  2800 x 5120
//      2483  3137

                int width = 2800;
                int height = 5120;
                int startX = 317;
                int startY = 1983;

                // 2347

                Thumbnails.of(item).sourceRegion(startX, startY, width - (startX << 1), height - startY - ((width - startX) / 2) + 440).scale(1)
                        .toFile(outFile.getAbsolutePath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public static void main(String[] args) throws IOException {
        File path = new File("D:\\tangzhichao\\pics.xlsx");
        XSSFWorkbook XSSfWorkbook = new XSSFWorkbook(Files.newInputStream(Paths.get(path.getAbsolutePath())));
        File pngDir = new File("D:\\tangzhichao\\png_cut");
        File[] listFile = pngDir.listFiles();
        int row = 0;
        int col = 0;
        for (int i = 0; i < listFile.length; i++) {
            File item = listFile[i];
            if (!item.getName().toLowerCase().endsWith(".png")) {
                continue;
            }
            if (i != 0 && i % 3 == 0) {
                row++;
                col = 0;
            }
            System.out.println("行：" + row);
            System.out.println("列：" + col);
            System.out.println("图片"+ item.getAbsolutePath());
            //图片文件  我这儿使用的是本地文件
            byte[] bytes = Files.readAllBytes(Paths.get(item.getAbsolutePath()));
            int pictureIdx = XSSfWorkbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
            XSSFSheet sheet = XSSfWorkbook.getSheetAt(0);
//            XSSFPatriarch patriarch = sheet.getDrawingPatriarch();
//            //设置图片参数  前面4个参数是第一个单元格和第二个单元格X Y坐标  后面4个参数是单元格坐标
//            //例如 0 0 0 0 4 1 5 2就是把图片添加到第二行的第五个单元格里面(数字是从0开始计算)
//            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) col, row, (short) (col + 1), row + 1);
//            anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
//            patriarch.createPicture(anchor, pictureIdx);
        }
        try (FileOutputStream out = new FileOutputStream(path)) {
            //输出
            XSSfWorkbook.write(out);
        }
    }

    public static void main4(String[] args) {
        main1(args);
//        main2(args);
        main3(args);
    }

    /**
     * 转换全部的pdf
     *
     * @param fileAddress 文件地址
     * @param filename    PDF文件名
     * @param type        图片类型
     */
    public static void pdf2png(String fileAddress, String filename, String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File("D:\\tangzhichao\\pdf_qr");
        try {
            try (PDDocument doc = PDDocument.load(file)) {
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                for (int i = 0; i < pageCount; i++) {
                    BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                    // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                    ImageIO.write(image, type, new File(fileAddress + "\\" + filename + "_" + (i + 1) + "." + type));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 自由确定起始页和终止页
     *
     * @param pdfFile      文件地址
     * @param filename     pdf文件名
     * @param indexOfStart 开始页  开始转换的页码，从0开始
     * @param indexOfEnd   结束页  停止转换的页码，-1为全部
     * @param type         图片类型
     */
    public static void pdf2png(File pdfFile, File out, int indexOfStart, int indexOfEnd, String type) {
        // 将pdf装图片 并且自定义图片得格式大小
        try {
            try (PDDocument doc = PDDocument.load(pdfFile)) {
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                for (int i = indexOfStart; i < indexOfEnd; i++) {
                    BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                    // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                    ImageIO.write(image, type, out);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
